import React, { useEffect, useState } from "react";
import { SidebarStaff } from "../../../components/Sidebar";
import { ActiveReq, GetGrades, GetPairInfo, GetPairList, GetQuestions, GetSubmissionPath, UpdateActive } from "../../../api";
import "./index.less";
import { useParams } from "react-router-dom";
import { Grade, IPairing, Question } from "../../../utils/constant";
import { Button, Modal } from "antd";


const Index: React.FC = () => {
  const params = useParams();
  const assignmentId = +params.assignmentId!;
  const [pairList, setPairList] = useState<IPairing[]>([]);
  const [questions, setQuestions] = useState<Question[]>([]);
  const [grades, setGrades] = useState<Grade[]>([]);
  const [isGradeModalOpen, setIsGradeModalOpen] = useState<boolean>(false);
  const [isCommentModalOpen, setIsCommentModalOpen] = useState<boolean>(false);
  const [isRequestModalOpen, setIsRequestModalOpen] = useState<boolean>(false);
  const [challengeRequest, setChallengeRequest] = useState<ActiveReq>({pairId: -1, reason: ""});

  const fetchPairList = async () => {
    try {
      const {
        data: { data },
      } = await GetPairList(assignmentId);
      setPairList(data);
    } catch (e) {
      console.error(e);
    }
  };

  const fetchPairInfo = async (pairId: number) => {
    try {
      const {
        data: { data },
      } = await GetPairInfo(pairId);
      return data;
    } catch (e) {
      console.error(e);
    }
  }

  const fetchQuestionList = async () => {
    try {
      const res = await GetQuestions({ assignmentId });
      const { code, msg } = res;
      if (code !== "00000") {
        throw new Error(msg);
      }
      setQuestions(res.data);
    } catch (e: any) {
      console.error(e);
    }
  };

  const fetchGrades = async (pairId: number) => {
    try {
      const { data } = await GetGrades(pairId);
      const res = data['data'];
      res.sort(function(a: Grade, b: Grade){
        // sort according to rubricId in ascending (question) order
        return a.rubricId - b.rubricId;
      });
      setGrades(res);
    } catch (e) {
      console.error(e);
    }
  }

  const openReview = async (studentId: number, pairingId: number) => {
    try {
      const { data } = await GetSubmissionPath(studentId, assignmentId);
      const res = data['data'];
      window.location.href =
        "../../../../../pdfViewer.html?pdf_url=" +
        "http://localhost:8080/grade/getSubmissionFile/" +
        res.contentFileLoc +
        "&assignmentId=" +
        assignmentId +
        "&pairingId=" +
        pairingId +
        "&submissionId=" +
        res.id;
    } catch (e) {
      console.error(e);
    }
  }

  const openGradeModal = () => {
    setIsGradeModalOpen(true);
  };
  const closeGradeModal = () => {
    setIsGradeModalOpen(false);
  };
  const openCommentModal = () => {
    setIsCommentModalOpen(true);
  };
  const closeCommentModal = () => {
    setIsCommentModalOpen(false);
  };
  const openRequestModal = async (pairId: number) => {
    const pairInfo = await fetchPairInfo(pairId);
    setChallengeRequest({ "pairId": pairId, "reason": pairInfo["challengeReason"] });
    setIsRequestModalOpen(true);
  }
  const submitRequestModal = async(approve: boolean) => {
    if (approve) {
      await UpdateActive(challengeRequest, assignmentId, 1); // 1: APPROVED review
    }
    else {
      await UpdateActive(challengeRequest, assignmentId, 2); // 2: VOIDED review
    }
    setIsRequestModalOpen(false);
    fetchPairList();
  }
  const closeRequestModal = () =>{
    setIsRequestModalOpen(false);
  }

  useEffect(() => {
    fetchPairList();
    fetchQuestionList();
  }, []);
  return (
    <>
      <SidebarStaff></SidebarStaff>
      <div className="participation">
        <h4>Participation List:</h4>

        <table id="participation-table" >
          <thead>
            <tr>
              <th>Pairing ID</th>
              <th>Reviewee ID</th>
              <th>Reviewer ID</th>
              <th>Review</th>
              <th>Grade</th>
              <th>Comment</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody>
            {pairList.map((val, key) => {
              return (
                <tr key={key}>
                  <td>{val.id}</td>
                  <td>{val.studentId}</td>
                  <td>{val.markerId}</td>
                  <td>
                    <button
                      id="review-task-button"
                      onClick={() => openReview(val.studentId, val.id)}
                    >View Review</button>
                  </td>
                  <td>
                    <button
                      id="grade-task-button"
                      onClick={() => {
                        fetchGrades(val.id);
                        openGradeModal();
                      }}>View Grades
                    </button>
                  </td>
                  <td>
                    <button
                      id="comment-task-button"
                      onClick={() => {
                        fetchGrades(val.id);
                        openCommentModal();
                      }}>View Comments
                    </button>
                  </td>
                  {
                  val.active === 3 ? ( // Pending Challenge
                    <td>
                      <button
                        id="challenge-task-button"
                        onClick={() => {
                          openRequestModal(val.id);
                        }}>Pending Challenge Request
                      </button>
                    </td>
                  ) :
                  val.active === 2 ? ( // VOIDED
                    <td style={{color: "red"}}>VOIDED</td>
                  ) :
                  val.active === 1 ? ( // completed
                    <td>
                      <img src="/images/greentick.png" width="20"></img>
                    </td>
                  ) :
                  val.active === 0 ? ( // not completed
                    <td>
                      <img src="/images/greycross.png" width="20"></img>
                    </td>
                  ) : (<td></td>)
                  }
                </tr>
              );
            })}
          </tbody>
        </table>

        <Modal
          title="View Grades"
          open={isGradeModalOpen}
          onOk={closeGradeModal}
          onCancel={closeGradeModal}
        >
          {grades.map((val, key) => {
            return (
              <div key={key}>
                <p>Q{key+1}: <b>{val.grade}</b> / {questions.at(key)?.maxMark}</p>
              </div>
            )
          })}
        </Modal>
        <Modal
          title="View Comments"
          open={isCommentModalOpen}
          onOk={closeCommentModal}
          onCancel={closeCommentModal}
        >
          {grades.map((val, key) => {
            return (
              <div key={key}>
                <p>Q{key+1}: {val.comment}</p>
              </div>
            )
          })}
        </Modal>
        <Modal
          title="Challenge By Reviewee"
          open={isRequestModalOpen}
          onCancel={closeRequestModal}
          footer={[
            <Button key="1" style={{background:'#f94449'}} onClick={() => submitRequestModal(false)}>Reject</Button>,
            <Button key="2" style={{background:'#00cc00'}} onClick={() => submitRequestModal(true)}>Approve</Button>
          ]}
        >Do you want to approve or reject this review for pairing ID: <b>{challengeRequest.pairId}</b> ?
        <br></br>
        Reason: <b>{challengeRequest.reason}</b>
        <br></br>
        <br></br>
        <i>Please click on *View Review, *View Grades, or *View Comments button to see them.</i>
        </Modal>

      </div>
    </>
  );
};

export default Index;